#!/usr/bin/env python3
# -*- coding: utf-8 -*-


import logging
import os
import time
import threading
import uuid


class Log:
    _lock = threading.Lock()  # 添加一个锁

    def __init__(self):
        self.root_path = os.path.dirname(os.path.abspath(__file__))
        self.logger = logging.getLogger()  # 创建logger对象
        self.set_level('info')  # 默认设置级别为INFO

    def set_level(self, level):
        levels = {
            'debug': logging.DEBUG,
            'info': logging.INFO,
            'warning': logging.WARNING,
            'error': logging.ERROR
        }
        self.logger.setLevel(levels.get(level, logging.INFO))

    def __printconsole(self, level, message, transaction_id):
        logname = os.path.join(self.root_path, '../log', '{0}.log'.format(time.strftime('%Y-%m-%d')))

        with self._lock:  # 确保写入文件的操作是线程安全的
            # 创建一个handler，用于写入日志文件
            fh = logging.FileHandler(logname, 'a', encoding='utf-8')
            formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(transaction_id)s - %(message)s ')
            fh.setFormatter(formatter)

            # 给logger添加handler
            self.logger.addHandler(fh)

            # 记录日志
            getattr(self.logger, level)(message, extra={'transaction_id': transaction_id})

            # 移除handler
            self.logger.removeHandler(fh)
            fh.close()  # 关闭文件

    def debug(self, message, transaction_id="-"):
        self.__printconsole('debug', message, transaction_id)
    def info(self, message, transaction_id="-"):

        self.__printconsole('info', message, transaction_id)
    def warning(self, message, transaction_id="-"):
        self.__printconsole('warning', message, transaction_id)
    def error(self, message, transaction_id="-"):
        self.__printconsole('error', message, transaction_id)

